<template>
  <div class="ai-chat-container">
    <el-card class="chat-window">
      <template #header>
        <div class="chat-header">
          <el-icon><ChatDotRound /></el-icon>
          <span>AI 智能助手</span>
        </div>
      </template>

      <div class="chat-messages-container">
        <div class="chat-messages" ref="messagesContainer">
          <div
              v-for="(message, index) in messages"
              :key="index"
              :class="['message', message.sender]"
          >
            <div class="message-avatar">
              <el-avatar :icon="message.sender === 'user' ? User : Message" />
            </div>
            <div class="message-content">
              <div class="message-text">{{ message.text }}</div>
              <div class="message-time">{{ formatTime(message.timestamp) }}</div>
            </div>
          </div>
        </div>
      </div>

      <div class="chat-input-area">
        <el-input
            v-model="inputMessage"
            placeholder="请输入您的问题..."
            :disabled="isLoading"
            @keyup.enter="sendMessage"
            clearable
        >
          <template #append>
            <el-button
                :icon="isLoading ? Loading : Message"
                :disabled="!inputMessage.trim() || isLoading"
                @click="sendMessage"
            />
          </template>
        </el-input>

        <div class="chat-actions">
          <el-button
              type="primary"
              size="small"
              :icon="Refresh"
              @click="clearChat"
              :disabled="isLoading"
          >
            清空对话
          </el-button>
          <el-button
              type="success"
              size="small"
              :icon="Upload"
              @click="exportChat"
              :disabled="isLoading"
          >
            导出记录
          </el-button>
        </div>
      </div>
    </el-card>
  </div>
</template>

<script setup>
import { ref, onMounted, onUpdated, nextTick } from 'vue'
import {
  ChatDotRound,
  User,
  Loading,
  Refresh,
  Upload,
  Message
} from '@element-plus/icons-vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { QueryEmbeddings } from '@/api/graphFileApi.js'
import {userTokenStore} from "@/store/userTokenStore.js";

// 聊天消息
const messages = ref([
  {
    sender: 'ai',
    text: '您好！我是AI助手，请问有什么可以帮您的吗？',
    timestamp: new Date()
  }
])
const inputMessage = ref('')
const isLoading = ref(false)
const messagesContainer = ref(null)

// 滚动到底部
const scrollToBottom = () => {
  nextTick(() => {
    if (messagesContainer.value) {
      messagesContainer.value.scrollTop = messagesContainer.value.scrollHeight
    }
  })
}

// 格式化时间
const formatTime = (date) => {
  if (!date) return ''
  const d = new Date(date)
  return `${d.getHours()}:${d.getMinutes().toString().padStart(2, '0')}`
}

// 添加消息
const addMessage = (sender, text) => {
  messages.value.push({
    sender,
    text,
    timestamp: new Date()
  })
  scrollToBottom()
}

// 清空聊天
const clearChat = () => {
  ElMessageBox.confirm('确定要清空所有聊天记录吗？', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(() => {
    messages.value = [
      {
        sender: 'ai',
        text: '您好！我是AI助手，请问有什么可以帮您的吗？',
        timestamp: new Date()
      }
    ]
    scrollToBottom()
  })
}
const token = userTokenStore().token;
// 导出聊天记录
const exportChat = () => {
  const chatContent = messages.value
      .map(
          (msg) =>
              `[${formatTime(msg.timestamp)}] ${msg.sender === 'user' ? '您' : 'AI'}: ${msg.text}`
      )
      .join('\n\n')
  const blob = new Blob([chatContent], { type: 'text/plain' })
  const url = URL.createObjectURL(blob)
  const link = document.createElement('a')
  link.href = url
  link.download = `AI聊天记录_${new Date().toLocaleDateString()}.txt`
  link.click()
  URL.revokeObjectURL(url)
  ElMessage.success('聊天记录已导出')
}

// 发送消息（流式）
const sendMessage = async () => {
  const messageText = inputMessage.value.trim()
  if (!messageText) return

  addMessage('user', messageText)
  inputMessage.value = ''
  isLoading.value = true

  // 只添加一条空的 ai 消息
  const aiMsg = {
    sender: 'ai',
    text: '',
    timestamp: new Date()
  }
  messages.value.push(aiMsg)
  scrollToBottom()

  try {
    const response = await fetch('/api/ai/embeddings/query', {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json',
        'Authorization': token
      },
      body: JSON.stringify({ query: messageText })
    })

    if (!response.ok || !response.body) {
      throw new Error('网络响应异常')
    }

    const reader = response.body.getReader()
    const decoder = new TextDecoder('utf-8')
    let aiResponse = ''

    const processChunk = async () => {
      const { value, done } = await reader.read()
      if (done) {
        // 最终更新，确保最后一块数据被处理
        aiMsg.text = aiResponse
        isLoading.value = false
        return
      }

      const chunk = decoder.decode(value, { stream: true })
      aiResponse += chunk
      aiMsg.text = aiResponse  // 实时更新AI消息
      scrollToBottom()

      // 继续读取下一块
      processChunk()
    }

    // 开始处理流
    processChunk()

  } catch (error) {
    aiMsg.text = '抱歉，处理您的请求时出现了问题。请稍后再试。'
    ElMessage.error('获取响应时出错: ' + (error.message || error))
    isLoading.value = false
  }
}

onMounted(scrollToBottom)
onUpdated(scrollToBottom)
</script>

<style scoped>
.ai-chat-container {
  max-width: 600px;
  margin: 40px auto;
  padding: 24px 0;
}
.chat-window {
  border-radius: 16px;
  box-shadow: 0 4px 24px 0 rgba(0,0,0,0.10);
  background: linear-gradient(135deg, #232526 0%, #414345 100%);
}
.chat-header {
  display: flex;
  align-items: center;
  font-size: 1.2rem;
  font-weight: 600;
  color: #00eaff;
  gap: 8px;
}
.chat-messages-container {
  height: 400px;
  overflow-y: auto;
  background: rgba(30, 34, 44, 0.98);
  border-radius: 12px;
  margin-bottom: 16px;
  padding: 16px;
}
.chat-messages {
  display: flex;
  flex-direction: column;
  gap: 16px;
}
.message {
  display: flex;
  align-items: flex-start;
  gap: 12px;
}
.message.user .message-avatar .el-avatar {
  background: linear-gradient(90deg, #00eaff 0%, #005bea 100%);
  color: #fff;
}
.message.ai .message-avatar .el-avatar {
  background: linear-gradient(90deg, #ffd200 0%, #f7971e 100%);
  color: #232526;
}
.message-content {
  background: rgba(255,255,255,0.08);
  border-radius: 8px;
  padding: 10px 16px;
  color: #e0eaff;
  min-width: 60px;
  max-width: 400px;
  word-break: break-all;
  font-size: 1rem;
  box-shadow: 0 2px 8px 0 rgba(0,234,255,0.04);
}
.message-time {
  font-size: 0.8rem;
  color: #aaa;
  margin-top: 4px;
  text-align: right;
}
.chat-input-area {
  margin-top: 12px;
  display: flex;
  flex-direction: column;
  gap: 8px;
}
.chat-actions {
  display: flex;
  gap: 8px;
  margin-top: 4px;
  justify-content: flex-end;
}
</style>